package service

import (
	"choujiang/common/models"
	"choujiang/common/db"
	"fmt"
	"choujiang/common/utils"
	"strconv"
)

const (
	NEWS_VIEW_LOG = "BoxKey::leyouboxnewslog_"
)

func GetNewsList(user *model.User) ([]model.News, error) {
	news := make([]model.News, 0)
	err := db.MysqlEngine.Cols("id", "cover", "content", "title", "author", "desc", "view", "created_at", "qr_code").Where("status=?", 1).Desc("order").Find(&news)
	if err != nil {
		fmt.Printf("GetGameList err:%+v\n", err)
	}
	for i := 0; i < len(news); i++ {
		news[i].Cover = utils.AddPrefix(news[i].Cover)
		if news[i].QrCode != "" {
			news[i].QrCode = utils.AddPrefix(news[i].QrCode)
		}
		news[i].IsRead = readNews(user.Id, news[i].Id)
		news[i].FormatDate = utils.FormatDate(news[i].CreatedAt)
	}
	return news, nil
}

func GetReadNewsNum(user *model.User) int {
	redisKey := NEWS_VIEW_LOG + strconv.FormatInt(user.Id, 10)
	v := db.MainRedisClient.SMembers(redisKey)
	vSlice := v.Val()
	news := make([]model.News, 0)
	err := db.MysqlEngine.Cols("id", "cover", "content", "title", "author", "desc", "view").Where("status=?", 1).NotIn("id", vSlice).Desc("order").Find(&news)
	if err != nil {
		fmt.Printf("GetReadNewsNum err:%+v\n", err)
	}
	return len(news)
}

func GetTopLine() []model.News {
	news := make([]model.News, 0)
	err := db.MysqlEngine.Cols("id", "cover", "content", "title", "author", "desc", "view").Where("status=?", 1).Desc("order").Find(&news)
	if err != nil {
		fmt.Printf("GetGameList err:%+v\n", err)
	}
	for i := 0; i < len(news); i++ {
		news[i].Cover = utils.AddPrefix(news[i].Cover)
	}
	return news
}

func GetNewsDetail(nid int64) (*model.News, error) {
	news := new(model.News)
	_, err := db.MysqlEngine.ID(nid).Get(news)
	news.Content = PackageContent(news)
	news.FormatDate = utils.FormatDate(news.CreatedAt)
	news.Cover = utils.AddPrefix(news.Cover)
	if news.QrCode != "" {
		news.QrCode = utils.AddPrefix(news.QrCode)
	}
	return news, err
}

func PackageContent(news *model.News) string {
	reContent := news.Content
	return reContent
}

func ViewNews(user *model.User, news *model.News) {
	redisKey := NEWS_VIEW_LOG + strconv.FormatInt(user.Id, 10)
	db.MainRedisClient.SAdd(redisKey, news.Id)
	return
}

func readNews(userId, newsId int64) int64 {
	var reInt int64
	redisKey := NEWS_VIEW_LOG + strconv.FormatInt(userId, 10)
	v := db.MainRedisClient.SIsMember(redisKey, newsId)
	if v.Val() {
		reInt = 1
	}
	return reInt
}
